import { defineStore } from "pinia";
import { ref } from "vue";
import type { User } from "../types";
import { login as loginApi } from "../api/login";

export const useAuthStore = defineStore("auth", () => {
  const user = ref<User | null>(null);
  const isAuthenticated = ref(false);
  const isLoading = ref(false);

  const login = async (credentials: {
    phone: string;
    code: string;
    userType: "candidate" | "recruiter";
  }) => {
    isLoading.value = true;

    try {
      // 模拟API调用
      // await new Promise((resolve) => setTimeout(resolve, 1500))
      let resp = await loginApi({
        loginBizId: credentials.phone, // phone, // "13800138000"
        smsCode: credentials.code,
        userType: credentials.userType === "candidate" ? 0 : 1,
      });

      // console.log("登录返回响应: ", resp.result);

      user.value = {
        id: resp.result.id,
        name: resp.result.userName,
        avatar: resp.result.avatarUrl,
        role: resp.result.userType, // userType: 0 求职者 userType: 1 招聘方
      };
      isAuthenticated.value = true;

      // 保存到localStorage
      localStorage.setItem("user", JSON.stringify(user.value));
      localStorage.setItem("isAuthenticated", "true");

      return { success: true };

      // 模拟登录验证
      // if (credentials.code === "123456") {
      //   user.value = {
      //     id: "1",
      //     name: credentials.userType === "recruiter" ? "杜先生" : "张小明",
      //     avatar: "/placeholder.svg?height=100&width=100",
      //     role: credentials.userType,
      //   }
      //   isAuthenticated.value = true

      //   // 保存到localStorage
      //   localStorage.setItem("user", JSON.stringify(user.value))
      //   localStorage.setItem("isAuthenticated", "true")

      //   return { success: true }
      // } else {
      //   throw new Error("验证码错误")
      // }
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : "登录失败",
      };
    } finally {
      isLoading.value = false;
    }
  };

  const logout = () => {
    user.value = null;
    isAuthenticated.value = false;
    localStorage.removeItem("user");
    localStorage.removeItem("isAuthenticated");
  };

  const initAuth = () => {
    const savedUser = localStorage.getItem("user");
    const savedAuth = localStorage.getItem("isAuthenticated");

    if (savedUser && savedAuth === "true") {
      user.value = JSON.parse(savedUser);
      isAuthenticated.value = true;
    }
  };

  return {
    user,
    isAuthenticated,
    isLoading,
    login,
    logout,
    initAuth,
  };
});
